<template>
  <el-dialog draggable :title="title" :model-value="visible" @closed="close" width="450">
    <el-form label-width="90px" :rules="rules" :model="formData" ref="form" @submit="handleConfirm"
             v-loading="showLoading">
      <el-form-item label="名称" prop="name">
        <el-input
            v-model="formData.name"
            placeholder="请输入新公司名称"
        />
      </el-form-item>
      <el-form-item label="支出/收入" prop="isOut">
        <el-select
            v-model="formData.isOut"
            placeholder="请选择账单金额出入类型"
        >
          <el-option label="支出" :value="1"/>
          <el-option label="收入" :value="0"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit">确认</el-button>
        <el-button @click="close">关闭</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup>
import {usePersonAddBillCategory} from "@/composition/billSys/usePersonBill.js";
import {useCompanyBillCategoryAdd} from "@/composition/billSys/useCompanyBill.js";

const props = defineProps(['visible', 'title', 'isCompany', 'companyId']);
const emit = defineEmits(['update:visible', 'confirm', 'cancel']);
const {
  visible,
  title,
  isCompany,
  companyId,
} = toRefs(props);

watch(() => visible.value, () => {
  formData.value = {
    name: "",
    isOut: 1,
  };
  clearErrorTip();
});

const showLoading = ref(false);
const form = ref(null);
const formData = ref({
  name: '',
  isOut: 1,
});

const rules = reactive({
  name: [{required: true, message: '请输入账单类型名称', trigger: 'blur'}],
  isOut: [{required: true, message: '请选择账单金额出入类型', trigger: 'blur'}]
});

const handleConfirm = (e) => {
  e.preventDefault();
  form.value.validate(async (valid) => {
    if (!valid) {
      return;
    }
    showLoading.value = true;
    try {
      // 个人
      if (!isCompany.value) {
        await usePersonAddBillCategory(formData.value.name, formData.value.isOut);
      } else {
        await useCompanyBillCategoryAdd(companyId.value, formData.value.name, formData.value.isOut);
      }

    } catch (e) {
      console.log(e);
    }
    showLoading.value = false;
    emit('update:visible', false);
    emit('confirm', formData.value);
  });
};

const close = () => {
  emit('update:visible', false);
  emit('cancel');
};

const clearErrorTip = () => {
  form.value && form.value.clearValidate();
};

</script>

<style scoped lang="scss">

</style>
